import 'dart:io';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter_wan_android/manager/storage_manager.dart';

import 'dio_interceptor.dart';
import 'http_constant.dart';

///
/// 使用dio单例
///
class DioSingleton {
  DioSingleton._();

  static final _instance = DioSingleton._();

  factory DioSingleton.getInstance() => _instance;

  /// dio单例
  Dio _dio;

  ///
  /// 初始化Dio对象
  ///
  Dio getDio() {
    if (_dio != null) {
      return _dio;
    }

    /// 全局属性：请求前缀、连接超时时间、响应超时时间
    BaseOptions options = new BaseOptions(
      baseUrl: HttpConstant.BASE_URL,
      responseType: ResponseType.plain,
      connectTimeout: 300000,
      receiveTimeout: 300000,
    );
    _dio = new Dio(options);

    ///设置代理
    (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
        (HttpClient client) {
      ///设置代理端口
      // client.findProxy = (uri) {
      //   //proxy all request to localhost:8888
      //   return "PROXY 192.168.101.86:8888";
      // };
      ///设置证书代理
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
    };

    /// 添加拦截器
    _dio.interceptors

      ///添加日志输出器
      ..add(LoggerInterceptor())

      /// cookie持久化 异步
      ..add(CookieManager(
          PersistCookieJar(dir: StorageManager.temporaryDirectory.path)));
    return _dio;
  }
}
